package servlet;

import domain.Admin;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import service.LoginOrRegisterServiceImpl;
import util.TemplateEngineUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/adminLogin")
public class AdminLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String password=req.getParameter("password");
        String username=req.getParameter("username");


        TemplateEngine engine= TemplateEngineUtil.getTemplateEngine(req.getServletContext());
        WebContext context = new WebContext(req, resp, req.getServletContext());
        resp.setCharacterEncoding("utf-8");
        LoginOrRegisterServiceImpl adminLoginService = new LoginOrRegisterServiceImpl();
        Admin admin = adminLoginService.getUserInfo(username);
        if (admin != null && admin.getPassword().equals(password)) {
            //跳到主页面
            resp.sendRedirect("selectStudentsServlet");
        } else {
            engine.process("error.html",context,resp.getWriter());
        }


    }
}
